// pages/classic/classic.js
// import HTTP from '../../utils/http'
import classicModel from '../../models/classic'
import likeModel from '../../models/like'

let cm = new classicModel()
let lm = new likeModel()
// let http = new HTTP()

Page({

  /**
   * 页面的初始数据
   */
   data: {
    classicData: null,
    latest: true,
    oldest: false,
    likeStatus: false,
    likeNumber: 0
  },
   
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 将资源请求封装到model类中
    cm.getLatest((msg) => {
      this.setData({
        classicData: msg,
        latestIndex: msg.index,
        likeStatus: msg.like_status,
        likeNumber: msg.fav_nums
      })
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 用户点赞
   */
  onHeart: function (event) {
    let attitude = event.detail.attitude
    let url = attitude == 'like' ? 'like' : 'like/cancel'
    let artId = this.data.classicData.id
    let category = this.data.classicData.type
    lm.onLike(url, artId, category, () => {
      console.log('commit ' + attitude + ' success!')
    })
  },

  /**
   * 用户查看新期刊
   */
  onNewer: function (event) {
    this._updateClassic('next')
  },

  /**
   * 用户查看旧期刊
   */
  onOlder: function (event) {
    this._updateClassic('previous')
  },

  /**
   * 更新期刊暗中做的事儿
   */
  _updateClassic: function (direction) {
    let index = this.data.classicData.index
    cm.getClassic(index, direction, (msg) => {
      this.setData({
        classicData: msg,
        latest: cm.islatest(msg.index),
        oldest: cm.isOldest(msg.index)
      })
      this._setLikeStatus(msg.type, msg.id)
    })
  },

  _setLikeStatus: function (category, artId) {
    lm.getLikeStatus(category, artId, (msg) => {
      this.setData({
        likeStatus: msg.like_status,
        likeNumber: msg.fav_nums
      })
    })
  }
})